<?php

namespace app\school\service;

use think\Db;
use think\Exception;
use think\facade\Config;

class DataTable
{
    /**
     * 获取数据表信息
     * @param  $table string
     * @return  array
     * @throws Exception
     */
    public static function getTableInfo($table)
    {
        $prefix = Config::get('database.prefix');
        if (stripos($table, $prefix) === 0) { //如果有表前缀
            $type = 'table'; //以Db::table()形式查询
        } else {
            $type = 'name'; //以Db::name()形式查询，不需要前缀
            $table = $prefix . $table;
        }
        $info = Db::query("SHOW TABLE STATUS LIKE '{$table}'", [], TRUE);
        if (empty($info[0])) {
            throw new Exception("table not found");
        }
        return [
            'type'  => $type,
            'info'  => $info[0]
        ];
    }

    /**
     * 获取数据表字段信息
     * @param $dbname string 数据库名
     * @param $tablename string 表名
     * @return array
     */
    public static function getFieldInfo($dbname,$tablename){
        $sql = "SELECT * FROM `information_schema`.`columns` "
            . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
            . "ORDER BY ORDINAL_POSITION";
        return Db::query($sql, [$dbname, $tablename]);
    }

}